﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Dapper;

namespace AutoPartsSearch.Domain.Common
{
    public class QueryExecutor
    {
        public static IEnumerable<T> QueryProcedure<T>(string procedureName, object param = null)
        {
            using (var connection = new DbContext().Connection)
            {
                return connection.Query<T>(procedureName, param, null, true, null, CommandType.StoredProcedure).ToList();
            }
        }

        public static int ExecuteProcedure(string procedureName, object param = null)
        {
            using (var connection = new DbContext().Connection)
            {
                return connection.Execute(procedureName, param, null, null, CommandType.StoredProcedure);
            }
        }

        public static IEnumerable<T> QueryDynamic<T>(string procedureName, Action<T, dynamic> reader, object param = null)
            where T : class, new()
        {
            using (var connection = new DbContext().Connection)
            {
                var result = connection.Query(procedureName, param, null, false, null, CommandType.StoredProcedure).ToList();
                return result.Select(x =>
                {
                    var t = new T();
                    reader(t, x);
                    return t;
                });
            }
        }
    }
}
